package java6681.lesson06;

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;

/**
 * @author Junichiro
 * @description 统计字符串中每个字符出现的次数
 * @date 2021-04-10 21:35
 **/

/*aababcabcdabcde*/
public class Counter6681 {
    public static void main(String[] args) {
        /*定义一个字符串*/
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个字符串：");
        String line = sc.nextLine();
        count6681(line).forEach(new BiConsumer<Character, Integer>() {
            @Override
            public void accept(Character key, Integer value) {
                System.out.println(key + "出现" + value + "次");
            }
        });
    }

    private static Map<Character, Integer> count6681(String str) {
        /*定义一个TreeMap集合*/
        TreeMap<Character, Integer> tm = new TreeMap<>();
        /*把字符串转换为字符数组*/
        char[] chs = str.toCharArray();
        /*遍历字符数组，得到每一个字符*/
        for (char c : chs) {
            tm.compute(c, new BiFunction<Character, Integer, Integer>() {
                @Override
                public Integer apply(Character character, Integer value) {
                    return value == null ? 1 : value + 1;
                }
            });
        }
        return tm;
    }
}
